package com.data.controllers.response;

import com.data.controllers.constants.ErrorConstants;
import org.springframework.http.HttpStatus;

import java.util.HashMap;
import java.util.Map;


public class BaseResponse<T> {

    private Integer code;

    private String msg;

    private Integer httpStatus;

    private int total;

    private Object data;

    private BaseResponse() {}

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public Integer getHttpStatus() {
        return httpStatus;
    }

    public void setHttpStatus(Integer httpStatus) {
        this.httpStatus = httpStatus;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public int getTotal() { return total; }

    public void setTotal(int total) { this.total = total; }

    /**
     * 创建响应体，成功返回，设置返回的数据
     * 
     * @param data
     * @return 响应体
     */
    public static <E> BaseResponse<E> build(E data, int total) {

        return build(HttpStatus.OK.value(), ErrorConstants.Errors.SUCCESS, data, total);
    }

    /**
     * 创建响应体
     * @return 响应体
     */
    public static <E> BaseResponse<E> error(E msg) {

        return build(HttpStatus.INTERNAL_SERVER_ERROR.value(), ErrorConstants.Errors.FAIL, msg, -1);
    }


    /**
     * 创建响应体，成功返回，设置返回的数据，单独设置http状态码
     * 
     * @param httpStatus HTTP状态码
     * @param data
     * @return 响应体
     */
    public static <E> BaseResponse<E> build(int httpStatus, E data , int total) {
        return build(httpStatus, ErrorConstants.Errors.SUCCESS, data, total);
    }

    /**
     * 创建响应体，有错误，但http状态仍是HttpStatus.OK
     * 
     * @param error 错误信息
     * @return 响应体
     */
    public static <E> BaseResponse<E> build(ErrorConstants.Errors error) {
        return build(HttpStatus.OK.value(), error, null,0);
    }

    /**
     * 创建响应体，有错误，单独设置http状态码
     * 
     * @param httpStatus HTTP状态码
     * @param error 错误信息
     * @return 响应体
     */
    public static <E> BaseResponse<E> build(int httpStatus, ErrorConstants.Errors error) {
        return build(httpStatus, error, null,0);
    }

    /**
     * 创建响应体。
     * 
     * @param httpStatus HTTP状态码
     * @param error 错误信息
     * @param data 返回的数据
     * @return 响应体
     */
    public static <E> BaseResponse<E> build(int httpStatus, ErrorConstants.Errors error, E data, int total) {
        BaseResponse<E> response = new BaseResponse<>();
        Map<String, Object> wdata = new HashMap<String, Object>();
        wdata.put("records",data);
        wdata.put("total",total);
        response.data = wdata;
        response.total=total;
        response.httpStatus = httpStatus;
        response.code = error.getCode();
        response.msg = error.getMessage();
        return response;
    }
}
